﻿using STHPMS1.Common.C_Entity;
using STHPMS1.Common.C_Entity.Stmpms1;
using STHPMS1.ICore;
using STHPMS1.ICore.I_Core;
using STHPMS1.ICore.I_UI;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Reflection;
using System.IO;
using STHPMS1.ICore.I_Serv;
using STHPMS1.Common.C_Extension; 

namespace STHPMS1.Web.W_Controller
{
    [RoutePrefix("api/rdfwd")]
    public class S_RdfwdPage1Controller : STHPMS1.Web.W_Core.MyController
    {
        [Route("")]
        [Route("page/{page?}", Name = "GetrdfwdByPage")]
        [Route("rows/{rows?}")]
        [Route("page/{page?}/rows/{rows?}")]
        public IHttpActionResult Get(string road = null, DateTime? checkDate = null, int page = 1, int rows = 10)
        {
            int p = page;
            int s = rows;

            PagingInfo info = new PagingInfo();
            info.PageIndex = p > 0 ? p - 1 : 0;
            info.PageSize = s;
            info.TotalRecords = 0;

            Expression<Func<S_Rdfwd, bool>> exp = null;
            if (((road != null && road.ToString().Length > 0)) && (checkDate != null))
            {
                exp = pre => (pre.Rdwayid == road.ToString()) && (pre.Svydata == checkDate);
            }
            else if (road != null && road.ToString().Length > 0)
            {
                exp = pre => pre.Rdwayid == road.ToString();
            }
            else if (checkDate != null)
            {
                exp = pre => pre.Svydata == checkDate;
            }


            var data = this.Scene.Bll.S_Rdfwd.Get<S_Rdfwd>(exp, info).ToArray();
            if (data == null) return NotFound();

            var result = new { rows = data, total = info.TotalRecords };

            return Ok(result);
        }

        [Route("")]
        public HttpResponseMessage Post(S_Rdfwd entity)
        {
            if (entity.Fwdid == null)
                entity.Fwdid = MyApp.Locator.GetInstance<IKeyGenrateService>().NewFwdId(entity);
            entity.Importdate = DateTime.Now;
            this.Scene.Bll.S_Rdfwd.Save(entity);

            var response = Request.CreateResponse(HttpStatusCode.Created);
            // Generate a link to the new book and set the Location header in the response.
            string uri = Url.Link("GetrdfwdByPage", new { page = 1 });
            response.Headers.Location = new Uri(uri);

            return response;
        }

        [Route("")]
        public void Delete(S_Rdfwd entity)
        {
            this.Scene.Bll.S_Rdfwd.Remove(entity);
        }



        /// <summary>
        /// 上传数据处理
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="rdid">路线编号</param>
        /// <param name="dir">调查方向</param>
        /// <returns></returns>
        [Route("saveFile")]
        public HttpResponseMessage PostSaveFile(string file)
        {
            DataTable entity = null;//实体数据
            Excel_BaseImportData exData = null;//导入数据
            if (File.Exists(file))
            {
                try
                {
                    int startRow = 0;//Excel列头位置

                    DataTable dt = Common.C_Excel.ExcelTool.GetDataTableFromExcel(file, startRow);//获取Excel的DataTable
                    //验证Excel表头格式?
                    entity = GetData(dt, startRow);//将要导入的实体Table
                    exData = new Excel_BaseImportData(new S_Rdfwd());//弯沉实体
                    exData.DtSource = entity;
                    exData.TableName = "S_RDFWD"; //弯沉
                    this.Scene.Bll.Excel.ImportData(exData);

                }
                catch (Exception ex)
                {
                    File.Delete(file);//删除上传数据
                    //抛出错误
                    var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(ex.Message),
                        ReasonPhrase = "Server Error"
                    };
                    throw new HttpResponseException(response);
                }
            }
            else
            {
                //抛出错误
                var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("服务器未能保存上传文件，请联系管理员"),
                    ReasonPhrase = "Server Error"
                };
                throw new HttpResponseException(response);
            }
            var res = Request.CreateResponse(HttpStatusCode.Created);
            string uri = Url.Link("GetrdfwdByPage", new { page = 1 });
            res.Headers.Location = new Uri(uri);

            return res;
        }



        /// <summary>
        /// 反射获取对象的所有属性
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private PropertyInfo[] GetAllProperty(object t)
        {
            Type temp = t.GetType();
            return temp.GetProperties();
        }
        /// <summary>
        /// 获取交通量实体的DataTable
        /// </summary>
        /// <param name="excel">导入excel</param>
        /// <param name="Rdwayid">路线编号</param>
        /// <param name="dir">调查方向</param>
        /// <returns></returns>
        private DataTable GetData(DataTable excel, int startRow)
        {

            DataTable kh = new DataTable();
            PropertyInfo[] propertys = GetAllProperty(new S_Rdfwd());
            foreach (PropertyInfo p in propertys)
            {
                kh.Columns.Add(new DataColumn(p.Name.ToUpper()));
            }
            kh.Columns.Add(new DataColumn("index")); //记录错误行号
            if (excel.Rows.Count == 0)
            {
                throw new Exception("Excel没有数据");
            }
            int index = startRow + 1;
            foreach (DataRow r in excel.Rows)
            {

                string _dir = r[excel.Columns.Count - 1].ToString();//方向  
                if (Common.C_Enum.DirectionEnum.All13.GetEnumDescription() == _dir)
                {
                    _dir = Common.C_Enum.DirectionEnum.All13.GetEnumValue().ToString();
                }
                else if (Common.C_Enum.DirectionEnum.Up11.GetEnumDescription() == _dir)
                {
                    _dir = Common.C_Enum.DirectionEnum.Up11.GetEnumValue().ToString();
                }
                else if (Common.C_Enum.DirectionEnum.Down12.GetEnumDescription() == _dir)
                {
                    _dir = Common.C_Enum.DirectionEnum.Down12.GetEnumValue().ToString();
                }

                string _svydata = r[2].ToString();//观测时间
                string _RDWAYID = r[0].ToString();//路线编号
                string _SURVEYER = r[3].ToString();//检测人员
                string _DEVICE = r[1].ToString();//设备
                double _fwdmp = Convert.ToDouble(r[4]);//测站桩号
                string _LOAD = r[5].ToString();//荷载
                string _DONE = r[6].ToString();//D1
                string _DTWO = r[7].ToString();//D2
                string _DTHREE = r[8].ToString();//D3
                string _DFOUR = r[9].ToString();//D4
                string _DFIVE = r[10].ToString();//D5
                string _DSIX = r[11].ToString();//D6
                string _DSEVE = r[12].ToString();//D7
                string _DEIG = r[13].ToString();//D8
                string _DNIN = r[14].ToString();//D9
                string _PVMT_TEMP = r[15].ToString();//沥青温度
                string _AIR_TEMP = r[16].ToString();//空气温度
                string _IMPORTDATE = DateTime.Now.ToShortDateString();
                string _fwdid = _RDWAYID + "_" + _fwdmp + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");

                DataRow dr = kh.NewRow();
                dr["FWDID"] = _fwdid;
                dr["DIRECTION_DICTID"] = _dir;
                dr["SVYDATA"] = _svydata;
                dr["RDWAYID"] = _RDWAYID;
                dr["FWDMP"] = _fwdmp;
                dr["SURVEYER"] = _SURVEYER;
                dr["DEVICE"] = _DEVICE;
                dr["LOAD"] = _LOAD == "" ? "0" : _LOAD;
                dr["DONE"] = _DONE == "" ? "0" : _DONE;
                dr["DTWO"] = _DTWO == "" ? "0" : _DTWO;
                dr["DTHREE"] = _DTHREE == "" ? "0" : _DTHREE;
                dr["DFOUR"] = _DFOUR == "" ? "0" : _DFOUR;
                dr["DFIVE"] = _DFIVE == "" ? "0" : _DFIVE;
                dr["DSIX"] = _DSIX == "" ? "0" : _DSIX;
                dr["DSEVE"] = _DSEVE == "" ? "0" : _DSEVE;
                dr["DEIG"] = _DEIG == "" ? "0" : _DEIG;
                dr["DNIN"] = _DNIN == "" ? "0" : _DNIN;
                dr["PVMT_TEMP"] = _PVMT_TEMP == "" ? "0" : _PVMT_TEMP;
                dr["AIR_TEMP"] = _AIR_TEMP == "" ? "0" : _AIR_TEMP;
                dr["IMPORTDATE"] = _IMPORTDATE;
                dr["index"] = index++;
                kh.Rows.Add(dr);

            }
            return kh;
        }


        /// <summary>
        /// 上传返回服务器路径
        /// </summary>
        [Route("uploadFile")]
        public void PostUploadFile()
        {
            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string uploadPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Upload") + "\\";
            string PhysicalPath = "";
            if (hfc.Count > 0)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                PhysicalPath = uploadPath + hfc[0].FileName;
                hfc[0].SaveAs(PhysicalPath);
            }

            System.Web.HttpContext.Current.Response.Write(PhysicalPath);
            System.Web.HttpContext.Current.Response.End();
        }

        
    }
}